package com.heima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.mapper.TbBusinessMapper;
import com.heima.mapper.TbNodeMapper;
import com.heima.pojo.TbNode;
import com.heima.pojo.TbVendingMachine;
import com.heima.mapper.TbVendingMachineMapper;
import com.heima.pojo.dto.TbVendingMachineDto;
import com.heima.pojo.vo.PageResponse;
import com.heima.pojo.vo.TbVendingMachineVo;
import com.heima.service.ITbVendingMachineService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Random;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author AkiRinko
 * @since 2024-06-08
 */
@Service
@RequiredArgsConstructor
public class TbVendingMachineServiceImpl extends ServiceImpl<TbVendingMachineMapper, TbVendingMachine> implements ITbVendingMachineService {

    private final TbNodeMapper tbNodeMapper;

    private final TbVendingMachineMapper tbVendingMachineMapper;

    /**
     * 设备搜索
     *
     * @param pageIndex
     * @param pageSize
     * @param innerCode
     * @return
     */
    @Override
    public PageResponse<TbVendingMachineVo> selectVm(Integer pageIndex, Integer pageSize, String innerCode) {
        Page<TbVendingMachineVo> page = new Page<>(pageIndex, pageSize);

        Page<TbVendingMachineVo> result = tbVendingMachineMapper.selectVm(innerCode, page);

        return PageResponse.of(result);
    }

    /**
     * 新增设备
     *
     * @param dto
     */
    @Override
    public void insertVm(TbVendingMachineDto dto) {
        TbVendingMachine tbVendingMachine = BeanUtil.copyProperties(dto, TbVendingMachine.class);
        TbNode node = tbNodeMapper.selectById(dto.getNodeId());

        tbVendingMachine.setBusinessId(node.getBusinessId());
        tbVendingMachine.setRegionId(node.getRegionId());
        tbVendingMachine.setOwnerId(node.getOwnerId());
        tbVendingMachine.setCityCode(node.getAreaCode());
        tbVendingMachine.setCreateTime(LocalDateTime.now());
        tbVendingMachine.setUpdateTime(LocalDateTime.now());
        tbVendingMachine.setLastSupplyTime(LocalDateTime.now());

        tbVendingMachineMapper.insert(tbVendingMachine);

        LambdaQueryWrapper<TbVendingMachine> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbVendingMachine::getInnerCode, "000");
        TbVendingMachine one = tbVendingMachineMapper.selectOne(wrapper);

        one.setInnerCode("010" + one.getId());

        tbVendingMachineMapper.updateById(one);
    }
}
